<template>
  <view class="goods goods-container">
    <Base ref="Base" :mode="mode" />
    <Recommend ref="Recommend" :mode="mode" />
    <Params ref="Params" :mode="mode" />
    <Stock ref="Stock" :mode="mode" />
    <Describe ref="Describe" :mode="mode" />
    <Footer @save="handleSave" @cancel="handleCancel" />
  </view>
</template>

<script>
import Base from "./components/Base.vue";
import Recommend from "./components/Recommend.vue";
import Params from "./components/Params.vue";
import Stock from "./components/Stock.vue";
import Describe from "./components/Describe.vue";
import Footer from "./components/Footer.vue";
import { mapActions, mapGetters, mapMutations, mapState } from "vuex";
import schema from "async-validator";
import {
  checkPrice,
  checkStock,
  maxStock,
  maxPrice
} from "../../utils/validator";
export default {
  components: { Base, Recommend, Params, Stock, Describe, Footer },
  data() {
    return {
      mode: "add",
      formData: {
        shopId: "",
        catId: "",
        title: "",
        price: "",
        isRecommend: "",
        image: "",
        desc: "",
        props: [
          //   {
          //     "key": "辣度",
          //     "values": ["不辣", "微辣", "特辣"]
          //   }
        ],
        skuList: []
      }
    };
  },
  computed: {
    ...mapGetters({
      shopId: "shopId"
    }),
    ...mapState({
      goodsInfo: state => state.goods.goodsInfo
    }),
    rules() {
      return {
        catId: { type: "number", required: true, message: "请选择商品分类" },
        title: [
          { type: "string", required: true, message: "请填写商品标题" },
          { max: 20, required: true, message: "商品标题不能超过20字" }
        ],
        price: [
          { required: true, message: "请填写商品价格" },
          { type: "number", validator: checkPrice }
        ],
        image: { type: "string", required: true, message: "请上传商品图片" },
        desc: { type: "string" },
        props: { type: "array" },
        skuList: { type: "array" }
      };
    }
  },
  onLoad(query) {
    this.formData.catId = query.catId;
    if (query.id) {
      this.formData = this.goodsInfo;
      this.mode = "modify";
    }
  },
  onBackPress() {
    this.INIT_GOODS_INFO();
    return false;
  },
  mounted() {
    this.init();
  },
  methods: {
    ...mapActions({
      postGoods: "postGoods",
      putGoods: "putGoods"
    }),
    ...mapMutations({
      ADD_NEW_GOODS: "ADD_NEW_GOODS",
      UPDATE_GOODS_ITEM: "UPDATE_GOODS_ITEM",
      INIT_GOODS_INFO: "INIT_GOODS_INFO"
    }),
    init() {
      if (this.formData.catId) {
        this.$refs.Base.setCatId(this.formData.catId);
      }
    },
    getFormData() {
      let Base = this.$refs.Base.getData();
      let Recommend = this.$refs.Recommend.getData();
      let Params = this.$refs.Params.getData();
      let Stock = this.$refs.Stock.getData();
      let Describe = this.$refs.Describe.getData();

      let formData = {
        ...Base,
        ...Recommend,
        ...Params,
        ...Stock,
        ...Describe,
        shopId: Number(this.shopId),
        catId: Number(Base.catId)
      };
      this.checkSkuList(formData);
      return formData;
    },
    // 检查skulist格式是否正确，并剔除无效sku
    checkSkuList(formData) {
      if (formData.skuList.length > 1) {
        let haveNoSpecIndex = formData.skuList.findIndex(
          v => !v.spec && !v.isDelete
        );
        let haveAvailableSpecSku = formData.skuList.some(v => !v.isDelete); // 是否有新的有规格sku
        if (haveNoSpecIndex > -1 && haveAvailableSpecSku) {
          formData.skuList[haveNoSpecIndex].isDelete = true;
        }
      }
      // 当只有一个sku时
      if (formData.skuList.length == 1) {
        // 有规格时，价格库存以sku为准
        if (formData.skuList[0].spec) {
          formData.price = formData.skuList[0].price;
          formData.stock = formData.skuList[0].stock;
        } else {
          formData.skuList[0].price = formData.price;
          formData.skuList[0].stock = formData.stock;
        }
      }
      // 当没有sku时，设置默认sku
      if (formData.skuList.length == 0) {
        formData.skuList.push({
          price: formData.price,
          stock: formData.stock
        });
      }
      // 所有都删除时
      let allDelete = formData.skuList.every(v => v.isDelete); // 是否都删除了
      if (allDelete) {
        formData.skuList.push({
          price: formData.price,
          stock: formData.stock
        });
      }
      formData.skuList = formData.skuList.filter(v => !(!v.id && v.isDelete));
    },
    handleSave() {
      let validator = new schema(this.rules);
      let formData = this.getFormData();
      validator.validate(formData, (errors, fields) => {
        if (errors) {
          uni.showToast({
            icon: "none",
            title: errors[0].message
          });
        } else {
          this.submit(formData);
        }
      });
    },
    submit(formData) {
      uni.showLoading({
        mask: true
      });
      if (this.mode == "add") {
        this.postGoods(formData)
          .then(res => {
            if (!res.code) {
              // if(res.data.skuList.)
              this.ADD_NEW_GOODS(res.data);
              this.$back();
            }
          })
          .finally(e => {
            uni.hideLoading();
          });
      } else {
        let params = { ...formData, id: this.goodsInfo.id };
        this.putGoods(params)
          .then(res => {
            if (!res.code) {
              // this.UPDATE_GOODS_ITEM(params);
              this.$back();
            }
          })
          .finally(e => {
            uni.hideLoading();
          });
      }
    },
    handleCancel() {
      this.$back();
    }
  }
};
</script>

<style lang="scss">
page {
  background-color: $uni-bg-color-grey;
}
.goods-container {
  padding-bottom: 200rpx;
}
</style>
